package cn.cdeden.knowledge.controller.team;


import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.LatelyUserTeam;
import cn.cdeden.knowledge.domain.Team;
import cn.cdeden.knowledge.domain.TeamRole;
import cn.cdeden.knowledge.domain.dto.TeamMemberDto;
import cn.cdeden.knowledge.domain.dto.TeamMemberQueryParam;
import cn.cdeden.knowledge.enums.ResultEnum;
import cn.cdeden.knowledge.enums.TeamParamEnum;
import cn.cdeden.knowledge.enums.TeamTypeEnum;
import cn.cdeden.knowledge.service.*;
import cn.cdeden.system.api.RemoteUserService;
import cn.cdeden.system.api.model.LoginUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Chen
 * @date 2022-09-06
 **/
@Controller
@Slf4j
//@Api(tags = "团队成员管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/teamMember")
public class TeamMemberController {

    private final TeamMemberService teamMemberService;

    private final TeamRoleService teamRoleService;

    private final TeamRelevanceRoleService teamRelevanceRoleService;

    private final TeamService teamService;

    private final LatelyUserTeamService latelyUserTeamService;
    @DubboReference
    private final RemoteUserService remoteUserService;


    //    @Log("查询团队成员")
//    @ApiOperation("查询团队成员")
    @GetMapping(value = "/query")
    @ResponseBody
    public R query(TeamMemberQueryParam query, Pageable pageable) {
        TableDataInfo<TeamMemberDto> teamMemberDtoPageInfo = teamMemberService.queryAll(query, pageable);
        return R.ok(teamMemberDtoPageInfo);
    }

//    @Log("查询团队成员用户")
//    @ApiOperation("查询团队成员用户")
    @GetMapping(value = "/queryUser")
    @ResponseBody
    public R queryUser(TeamMemberQueryParam query) {
        return R.ok(teamMemberService.queryUser(query));
    }

//    @Log("查询当前用户成员角色")
//    @ApiOperation("查询当前用户成员角色")
    @GetMapping(value = "/queryMemberRole")
    @ResponseBody
    public R queryMemberRole(@Param(value = "teamId") String teamId,@Param(value = "userId") Long userId) {
        List<TeamMemberDto> teamMemberDtoList = teamMemberService.getRole(teamId,remoteUserService.getUserInfo(userId));
        List<TeamRole> roleList = new ArrayList<>();
        for (TeamMemberDto teamMemberDto : teamMemberDtoList) {
            roleList.add(teamRoleService.getById(teamMemberDto.getRoleId()));
        }

        LoginUser user = LoginHelper.getLoginUser();
        LatelyUserTeam latelyUserTeam = new LatelyUserTeam();
        latelyUserTeam.setTeamId(Long.valueOf(teamId));
        latelyUserTeam.setUserId(user.getUserId());
        latelyUserTeamService.addlatelyTeam(latelyUserTeam);
        return R.ok(roleList);
    }

//    @Log("新增团队成员")
//    @ApiOperation("新增团队成员")
    @PostMapping(value = "/add")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public R add(@RequestBody List<TeamMemberDto> teamMemberDtos) {
        LoginUser user = LoginHelper.getLoginUser();

        Integer teamId = teamMemberDtos.get(0).getTeamId();
        Team team = teamService.getById(teamId);
        if (team.getType().equals(TeamTypeEnum.PROJECT_TEAM.getNum())){
            return R.fail("项目团队：“" + team.getTeamName() +"“ 不可修改");
        }
        if (!teamMemberService.checkPermission(String.valueOf(teamId), user, TeamParamEnum.JURISDICTION.getParam())){
            throw new RuntimeException("无权限分配！");
        }
        return R.ok(teamMemberService.addMembers(teamMemberDtos));
    }

//    @Log("修改团队成员角色")
//    @ApiOperation("修改团队成员角色")
    @PostMapping(value = "/updateUserRoleType")
    @Transactional(rollbackFor = Exception.class)
    public R updateUserRoleType(@RequestBody List<TeamMemberDto> teamMemberDtos) {
        LoginUser user = LoginHelper.getLoginUser();
        String teamId = String.valueOf(teamMemberDtos.get(0).getTeamId());

        Team team = teamService.getById(teamId);
        if (team.getType().equals(TeamTypeEnum.PROJECT_TEAM.getNum())){
            return R.fail("项目团队：“" + team.getTeamName() +"“ 不可修改");
        }

        if (!teamMemberService.checkPermission(teamId, user, TeamParamEnum.JURISDICTION.getParam())){
            return R.fail(ResultEnum.PERM_ERROR.getNum(),"无权限分配，请联系管理员");
        }
        for (TeamMemberDto teamMemberDto : teamMemberDtos) {
            teamRelevanceRoleService.updateRole(team.getHeadNodeId(),teamMemberDto.getObjectId(),teamMemberDto.getObjectType(),teamMemberDto.getRoleId());
            teamMemberService.updateById(teamMemberDto);
        }


        return R.ok(null);
    }

//    @Log("删除团队成员")
//    @ApiOperation("删除团队成员")
    @PostMapping(value = "/delete")
    @Transactional(rollbackFor = Exception.class)
    public R delete(@RequestBody List<TeamMemberDto> teamMemberDtos) {

        Team team = teamService.getById(teamMemberDtos.get(0).getTeamId());
        if (team.getType().equals(TeamTypeEnum.PROJECT_TEAM.getNum())){
            return R.fail("项目团队：“" + team.getTeamName() +"“ 不可修改");
        }

        for (TeamMemberDto teamMemberDto : teamMemberDtos) {
            if (!teamMemberService.checkPermission(String.valueOf(teamMemberDto.getTeamId()),LoginHelper.getLoginUser(), TeamParamEnum.JURISDICTION.getParam())){
                throw new RuntimeException("无权限分配！");
            }
            teamMemberService.delete(teamMemberDto);

        }
        return R.ok(true);
    }
}
